/* collection:BlueStraggler         http://blue.straggler.org
 * codebase:Grovecell
 * toolset:Feniseca
 * package:hardcoded
 * file:feniseca4script.groovy
 *
 * Copyright 2011-2013 Stellabs.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//package org.stellabs.grovecell.make;

/*
 * Feniseca was originally created to support Ant.
 * Indeed, in pure Java/Groovy environments better solutions already exist to load and execute Groovy scripts.
 * However in the event that someone wants to use the Feniseca mechanisms without Ant, some glue is required:
 * - In the script, the code below can be copied, or evaluated as a file or a string, etc.
 * 
 * Usage within a Groovy script:
 * use(Feniseca){initialize(<feniseca-root>)};
 * use(Feniseca){facility(<package>, <facility>[,<alias>]);}
 * 
 */

import groovy.lang.Script;

// Applicable to pure Groovy scripts
@Category(Script)
class Feniseca {
  static class Initializer{
    static def owner, root, fixer;
    Initializer(_owner,_root, packname, filename) {
      root = _root;
      owner = _owner;
      def fixator = owner.evaluate(new File(root+'/'+packname.replace('.', '/')+'/'+filename));
      fixer = fixator(root, owner.getBinding());
    }
    static Initializer instance;
  };

  boolean initialize(r,p="org.stellabs.grovecell.make",f="fixer_script.groovy") {
    def script = this; synchronized(script) {
      if (Initializer.instance) return false;
      Initializer.instance = new Initializer(this,r,p,f);
      return true; }
  }
  
  void facility(p, c, a="") {
    def script = this; synchronized(script) {
      assert script == Initializer.owner;
      if (""==a) a = c;
       script.evaluate("${a} = Feniseca.Initializer.instance.fixer.getFacility(\"${p}\", \"${c}\", \"${a}\");");
    }
  }

};


// Trick, -if loaded as a script- to get rid of "java.lang.InstantiationException: ..."
assert true;
